import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Col, Row, Spin, message } from 'antd';
import { useEffect, useRef } from 'react';
import {encryptWithSHA256} from '@/utils/crypto'
import { addUser, updateUser } from '@/services/userManageApi';

interface Props {
  open: boolean;
  data?: USER.UserModel | null;
  onFinish: () => void;
}

export default function UserEditDrawer(props: Props) {
  const formRef = useRef<ProFormInstance>();

  // 当抽屉打开且有数据时，设置表单初始值
  useEffect(() => {
    if (props.open && props.data) {
      // 处理头像URL，转换为完整的URL格式
      const avatarValue = props.data.avatar 
        ? [{
            uid: '-1',
            name: 'avatar.png',
            status: 'done',
            url: `http://www.gameback.cn/${props.data.avatar}~tplv-trmyndwfss-image.image`,
          }] 
        : [];
      
      formRef.current?.setFieldsValue({
        ...props.data,
        avatar: avatarValue,
      });
    }
  }, [props.data, props.open]);

  // 添加用户请求
  const { run: addUserRun, loading: addLoading } = useRequest(addUser, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功');
      props.onFinish?.();
    },
  });

  // 更新用户请求
  const { run: updateUserRun, loading: updateLoading } = useRequest(updateUser, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功');
      props.onFinish?.();
    },
  });
  
  // 处理头像URL，从完整URL中提取出需要保存的部分
  const transformAvatarUrl = (url: string) => {
    if (!url) return url;
    const baseUrl = 'http://www.gameback.cn/';
    const suffix = '~tplv-trmyndwfss-image.image';
    
    if (url.startsWith(baseUrl)) {
      return url.substring(baseUrl.length, url.indexOf(suffix));
    }
    return url;
  };

  return (
    <ModalForm
      formRef={formRef}
      open={props.open}
      width="50vw"
      title={props.data ? '编辑用户' : '新增用户'}
      drawerProps={{
        destroyOnClose: true,
        onClose: props.onFinish,
      }}
      onOpenChange={(_open) => !_open && props.onFinish()}
      onFinish={async (values: any) => {
        // 点击确定按钮时触发
        const params = { ...values };
        
        // 处理头像字段
        if (params.avatar && params.avatar.length > 0) {
          // 如果是文件对象数组（新上传的文件）
          if (params.avatar[0].originFileObj) {
            // 这里应该有文件上传逻辑，暂时保留原始文件名
            params.avatar = params.avatar[0].name;
          } else if (params.avatar[0].url) {
            // 如果是已有的URL，提取需要的部分
            params.avatar = transformAvatarUrl(params.avatar[0].url);
          }
        }
        
        if (props.data?.id) {
          // 更新用户
          await updateUserRun({ ...params, id: props.data.id });
        } else {
          // 添加用户
          delete params.confirmPassword
          params.password = encryptWithSHA256(params.password)
          await addUserRun(params);
        }
        return true;
      }}
    >
      <Spin spinning={false} tip="加载中...">
        <Row gutter={16}>
          <Col span={14} xs={24} sm={14}>

            <ProFormText
              name="name"
              label="姓名"
              width="md"
              rules={[{ required: true, message: '请填写姓名' }]}
              fieldProps={{ maxLength: 30, showCount: true }}
            />
            <ProFormText
              name="nickName"
              label="昵称"
              width="md"
              fieldProps={{ maxLength: 30, showCount: true }}
            />
            <ProFormText
              name="className"
              label="班级"
              width="md"
              fieldProps={{ maxLength: 30, showCount: true }}
            />
            <ProFormText
              name="stuNo"
              label="学号"
              width="md"
              fieldProps={{ maxLength: 30, showCount: true }}
            />
          </Col>
          <Col span={10} xs={24} sm={10}>
            <ProFormUploadButton
              name="avatar"
              label="头像"
              fieldProps={{
                listType: 'picture-card',
                // 自定义显示逻辑，处理完整URL
                itemRender: (originNode, file) => {
                  if (file.url && file.url.includes('gameback.cn')) {
                    // 已经是完整URL，直接显示
                    return (
                      <div className="ant-upload-list-item-thumbnail">
                        <img 
                          src={file.url} 
                          alt="avatar" 
                          style={{ width: '100%', height: '100%' }} 
                        />
                      </div>
                    );
                  }
                  return originNode;
                },
              }}
              transform={(value) => {
                // 表单提交时的转换
                return { avatar: value };
              }}
              max={1}
            />
            <ProFormSelect
              name="status"
              label="状态"
              width="md"
              options={[
                { label: '在校', value: '1' },
                { label: '毕业', value: '2' },
                { label: '休学', value: '3' },
                { label: '封禁', value: '4' },
              ]}
              required
            />
          </Col>
        </Row>
        <ProForm.Group>
          <ProFormText
            name="phone"
            label="手机号"
            width="md"
            fieldProps={{ maxLength: 11 }}
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            width="md"
            rules={[
              { type: 'email', message: '请输入正确的邮箱地址' },
            ]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="role"
            label="角色"
            width="md"
            options={[
              { label: '管理员', value: 'ADMIN' },
              { label: '教师', value: 'TEACHER' },
              { label: '学生', value: 'STUDENT' },
              { label: '小管家', value: 'MANAGER' },
            ]}
            rules={[{ required: true, message: '请选择角色' }]}
            disabled={formRef.current?.getFieldValue('role') !== 'TEACHER'}
          />
          <ProFormRadio.Group
            name="gender"
            label="性别"
            options={[
              { label: '男', value: 1 },
              { label: '女', value: 0 },
            ]}
          />
        </ProForm.Group>
        {!props.data && (
          <ProForm.Group>
            <ProFormText.Password
              name="password"
              label="密码"
              width="md"
              rules={[{ required: !props.data, message: '请输入密码' }]}
              fieldProps={{ maxLength: 20 }}
            />
            <ProFormText.Password
              name="confirmPassword"
              label="确认密码"
              width="md"
              rules={[
                { required: !props.data, message: '请确认密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
              fieldProps={{ maxLength: 20 }}
            />
          </ProForm.Group>
        )}
      </Spin>
    </ModalForm>
  );
}